package com.whl.sm.controller.dynamic;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whl.sm.common.result.Result;
import com.whl.sm.common.util.UploadUtils;
import com.whl.sm.controller.BaseController;
import com.whl.sm.model.dynamic.LikeOperate;
import com.whl.sm.model.dynamic.VDynamic;
import com.whl.sm.model.notice.Attachment;
import com.whl.sm.model.system.OrgUser;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.service.dynamic.LikeOperateService;
import com.whl.sm.service.dynamic.VDynamicService;
import com.whl.sm.service.notice.AttachmentService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.vo.DynamicUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhaolun
 * @since 2022-01-15
 */
@Slf4j
@RestController
@RequestMapping("/v-dynamic")
public class VDynamicController extends BaseController {

    @Autowired
    private VDynamicService dynamicService;

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Autowired
    private LikeOperateService likeOperateService;

    @Autowired
    private AttachmentService attachmentService;

    @Value("${ROOT_PATH}")
    private String rootPath;


    @RequestMapping("/list")
    public Result list(HttpServletRequest request){
        QueryWrapper queryWrapper = getLikeParam("content");
        queryWrapper.ne("is_del",1);
        queryWrapper.orderByDesc("create_time");
        Page<Object> resultPage = dynamicService.page(getPage(),queryWrapper);
        String userId = orgUserService.getCurrentUserId();
        List<Object> resultList = new ArrayList<>();
        resultList = resultPage.getRecords().stream().map(obj->{
            VDynamic dynamic = (VDynamic) obj;
            OrgUser user = orgUserService.getById(dynamic.getOperator());
            OrgUserInfo userInfo = orgUserInfoService.getByUserId(dynamic.getOperator());
            List<Attachment> linkImg = attachmentService.list(new QueryWrapper<Attachment>().
                    eq("data_id",dynamic.getId())
            );
            List<String> imgUrl = linkImg.size()>0?linkImg.stream().map(Attachment::getFile).collect(Collectors.toList()):new ArrayList<>();
            Boolean likeStatus = null;
            if (Objects.nonNull(userId)){
                List<LikeOperate> onLike = likeOperateService.list(new QueryWrapper<LikeOperate>()
                        .eq("dynamic_id",dynamic.getId())
                        .eq("operate",userId)
                );
                likeStatus = onLike.size()>0?true:false;
            }
            return new DynamicUserVo(dynamic,user,userInfo,imgUrl,likeStatus);
        }).collect(Collectors.toList());
        resultPage.setRecords(resultList);
        return Result.ok(resultPage);
    }

    @RequestMapping("/info/{id}")
    public Result viewInfo(@PathVariable("id") String id){
        VDynamic dynamic = dynamicService.getById(id);
        return Result.ok(dynamic);
    }

    @RequestMapping("/update")
    public Result update(@RequestBody VDynamic vDynamic){
        dynamicService.update(vDynamic);
        return Result.ok();
    }

    @RequestMapping("/publish")
    public Result publish(@RequestParam(value = "content",required = false) String content,
                          @RequestParam("tempId") String tempId,
                          @RequestParam("imgList") MultipartFile imgList,
                          HttpServletRequest request){
        String path = "/dynamic/linkImg";
        String userId = orgUserService.getCurrentUserId();
        if (Objects.nonNull(userId)){
            path += ("/"+userId);
        }
        try {
            List<Map<String,Object>> fileList = UploadUtils.saveFile(request,path,this.rootPath,"imgList");
            //String resultPath = "";
            if (fileList.size()>0){
                for (Map<String,Object> map : fileList){
                    Attachment attachment = new Attachment();
                    attachment.setDataId(tempId);
                    attachment.setDataType("DYNAMIC_PUBLISH");
                    attachment.setFile(String.valueOf(map.get("filePath")));
                    attachment.setFileSize(Integer.valueOf(map.get("fileSize")+""));
                    attachment.setFileName(String.valueOf(map.get("originalName")));
                    attachment.setFileType(String.valueOf(map.get("mimeType")));
                    attachmentService.update(attachment);
                }
            }

            if (Objects.nonNull(content)){
                Result publishResult =  dynamicService.publish(content,tempId);
                if (!publishResult.isOk()){
                    return publishResult;
                }
            }
        }catch (Exception e){
            log.error("小区动态发布图片上传失败:----->"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }

    @RequestMapping("/logDelete")
    public Result logicalDelete(@RequestBody List<String> idList){
        for (int i = 0; i <idList.size() ; i++) {
            dynamicService.update(new UpdateWrapper<VDynamic>()
                    .eq("id",idList.get(i))
                    .set("is_del",1)
            );
        }
        return Result.ok();
    }



}
